package com.penglecode.hash;

import java.util.ArrayList;
import java.util.List;
import java.util.zip.CRC32;
/**
 * hash算法及分布例子
 * 
 * @author pengpeng
 * @date 2013-6-5上午10:57:24
 * @version 1.0
 * @see [相关类/方法]
 * @since [产品/模块版本]
 */
public class HashServer {

	private String ipAddr;
	
	private int index;
	
	private List<String> keyList = new ArrayList<String>();
	
	public HashServer(String ipAddr, int index) {
		super();
		this.ipAddr = ipAddr;
		this.index = index;
	}

	public String getIpAddr() {
		return ipAddr;
	}

	public void setIpAddr(String ipAddr) {
		this.ipAddr = ipAddr;
	}

	public int getIndex() {
		return index;
	}

	public void setIndex(int index) {
		this.index = index;
	}

	public List<String> getKeyList() {
		return keyList;
	}

	public void setKeyList(List<String> keyList) {
		this.keyList = keyList;
	}

	protected static int newCompatHashingAlg(String key) {
        CRC32 checksum = new CRC32();
        checksum.update( key.getBytes() );
        int crc = (int) checksum.getValue();

        return (crc >> 16) & 0x7fff;
    }
	
	public String toString() {
		return "HashServer [ipAddr=" + ipAddr + ", index=" + index + "]";
	}

	public static void main(String[] args) {
		HashServer hs1 = new HashServer("192.168.1.100", 0);
		HashServer hs2 = new HashServer("192.168.1.101", 1);
		HashServer hs3 = new HashServer("192.168.1.102", 2);
		HashServer hs4 = new HashServer("192.168.1.103", 3);
		List<HashServer> hsList = new ArrayList<HashServer>();
		hsList.add(hs1);
		hsList.add(hs2);
		hsList.add(hs3);
		hsList.add(hs4);
		int servers = hsList.size();
		int total = 10000;
		for(int i = 0; i < 10000; i++){
			String key = "product-" + i;
			int hash = newCompatHashingAlg(key);
			int index = hash % servers;
			hsList.get(index).getKeyList().add(key);
			System.out.println("key = " + key + ", index = " + index);
		}
		for(int i = 0; i < hsList.size(); i++){
			int subTotal = hsList.get(i).getKeyList().size();
			System.out.println(">>> server : " + hsList.get(i) + " , " + subTotal + " , " + String.format("%1$.2f%%", (subTotal * 100.0 / total)));
		}
	}

}
